~{do
  -- http://www.mozilla.org/projects/netlib/http/http-caching-faq.html
  L:set_header("Cache-control", "no-cache")
  L:set_header("Cache-control", "no-store")
  L:set_header("Pragma", "no-cache")
  L:set_header("Expires", "0")
end}<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" dir="ltr">
<head>
<title>Renoise Matrix</title>
    <meta http-equiv="cache-control" content="no-cache" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <link type="text/css" href="/css/default.css" media="screen" rel="stylesheet" />

    <!-- required scripts -->
    <script type="text/javascript" src="/js/jquery-1.5.1.min.js"></script>
    <script type="text/javascript" src="/js/jquery.chromatable.js"></script>
    <script type="text/javascript" src="/js/jquery.scrollTo-min.js"></script>

    <link type="text/css" href="matrix.css" media="screen" rel="stylesheet" />

</head>

<body>
  <div id="center">
      <div id="playback_control"><b>Playback Control</b> &raquo; <b>Tempo:</b> <span id="tempo">n/a</span> - <b>Line:</b> <span id="line">?</span> / <span id="lines">?</span></div> 

      <div id="test-tools"></div>

      <div id="matrix_placeholder"><!-- Matrix Table goes here --></div>

      <div id="log"></div>

  </div>

  <script type="text/javascript">
    var debug = true;
    var logging = false;

    var autoscroll = false;

    var autoupdate = true;
    var autoupdater = null;
    var au_interval = 200;

    var client_id = ~{do
        local client = L:generate_client()
        OUT = client.id
      end};

    function set_sid(sid){
      $('.scheduled').removeClass('scheduled');
      $('.current_seq').removeClass('current_seq');
      $('#s'+sid).addClass('current_seq');
      if (autoscroll){
        $.scrollTo('.current_seq', 500);
      }
    }

    //s42t04
    function set_mute_state(data){
      $.each(data, function(k,v){
        $('#'+k).toggleClass('seq_mute', v);
        if (!v) {
          clearCell($('#'+k));
        } else {
          drawSeqMute($('#'+k));
        }
      });
    }
    
    // table;
    //[0] loop start (0=none)
    //[1] loop end (0=none)
    function set_seq_loop(arr){
      $('.seq_loop').removeClass('seq_loop');
      if (arr[0] > 0){
        for (i=arr[0];i<=arr[1];i++){
          $('#s'+i).addClass('seq_loop');
        }
      }
    }
    
    function set_tempo(bpm){
      $('#tempo').text(bpm);
    }
    
    function set_track_state(data){
        $('.t'+data.tid).toggleClass('off', data.state==2);
        $('.t'+data.tid).toggleClass('muted', data.state==3);
    }

    //TODO reflect track changes in data model/references
    function update_table(t, data, value){
        if (data.type == "swap") {

        } else if (data.type == "remove") {

        } else if (data.type == "insert") {
          if (typeof value == 'function') {

          } else {

          }
        }
    }

    //TODO reflect track changes in GUI
    function rearrange_tracks(data){

    }

    function set_playback_pos(line){
      $('#line').text(line);
    }

    function set_pattern_length(lines){
      $('#lines').text(lines);
    }
    
    function clearCell(elm){
      $(elm).html("");
    }

    function drawSeqMute(elm){
      var w = $(elm).width();
      var h = $(elm).height();
      $(elm).html('<img src="seq_mute.png" height="'+h+'" width="'+w+'" />');
    }

    function load_matrix_table(callback){
      //Get Matrix
      $.get('/matrix/matrix_table.lua', function(data){

        //Display Content
        $("#matrix_placeholder").html(data);

        //Floating Table Head
        $("#table_matrix").chromatable({
          height: "600px",
          width: "100%"
        });

        //Cell Mutes
        $('.seq_mute').each(function(){drawSeqMute(this);});
        
        //Initialize stuff
        set_pattern_length(lines);
        set_playback_pos(line);
        set_tempo(bpm);

        //Track Colors

        if (typeof callback == "function"){
          callback();
        }
      });
    }

    function log(str){
      if (debug==true && logging==true){
        $('#log').prepend("<p>"+str+"</p>");
      }
    }

    function update(data){
      log(data)
      //eventid:[k=v]
      data = $.parseJSON(data);
      $.each(data, function(k,event){
        switch(event.key) {
          case "line": set_playback_pos(event.value); break;
          case "sid": set_sid(event.value); break;
          case "lines": set_pattern_length(event.value); break;
          case "mutes_changed": set_mute_state(event.value); break;
          case "song_change": load_matrix_table(); break;
          case "seq_loop": set_seq_loop(event.value); break;
          case "tempo": set_tempo(event.value); break;
          case "track_state_changed": set_track_state(event.value); break;
          case "tracks_changed": rearrange_tracks(event.value); break;
        }
      });

    }
    
    function loop(){
      if (autoupdate){
        $.get('/matrix/get-song-updates.lua', {client_id: client_id}, function(data){ update(data); } );
      }
      setTimeout('loop()', au_interval);
    }
    
    function get_toggle_text(v) {
      var str = "enable";
      if (v) {
        str = "disable";
      }
      return str
    }

    $(document).ready(function(){
      $('body').prepend('<div id="gmenu"></div>');
      $('#gmenu').load('/menu.html');
    
      if (debug==true){
        $("#test-tools").append("<strong>Test Tools</strong> ");        
        $("#test-tools").append("Client ID: "+client_id+" ");
        $("#test-tools").append("<button id='update'>update manually</button>");
        $("#update").toggle(!autoupdate);
        $("#update").click(function(){
          $.get('/matrix/get-song-updates.lua', {client_id: client_id}, function(data){ update(data); } );
        });        
           
        //AUTO-UPDATE TOGGLE   
                
        $("#test-tools").append("<button id='autoupdate'>"
          +get_toggle_text(autoupdate)+" auto-update</button>");          
          
        $("#autoupdate").click(function(){
          autoupdate = !autoupdate
          log(get_toggle_text(autoupdate)+"d autoupdate");
          $("#autoupdate").text(get_toggle_text(autoupdate)+" auto-update");
          $("#update").toggle(!autoupdate);
        });
        
        //LOGGING TOGGLE
        
        $("#test-tools").append("<button id='logtoggle'>"
          +get_toggle_text(logging)+" logging</button>");
          
        $("#logtoggle").click(function(){
          logging = !logging
          log(get_toggle_text(logging)+"d logging");
          $("#logtoggle").text(get_toggle_text(logging)+ " logging");
        });
        

        $("#test-tools").css("display", "block");
        $("#log").css("display", "block");
      }

      //Polling Renoise for song changes
        load_matrix_table(loop);

    }); // end document ready

    //Track Mute
    $("#table_matrixwrapper th").live('click', function(){
      var id = $(this).attr('id'); //t03
      if (!id) 
        return false;
      var tid = id.substr(1);
      ~{do
         local url = Util:urlencode(
           "/Track Muting/Mute//Unmute/Track XX [Toggle]/Track #tid [Toggle]")
         url = url:gsub("%%23tid", "%%23'+tid+'")
         OUT = ("var url = '%s';"):format(url)
      end }

      var p = this;
      $.post(url, {ajax:true});
      return false;
    });

    //Track Hover
    var old_tid = 0;
    $("td").live('mouseover', function(){
      if (!$(this).hasClass('p')) return false;
      var id = $(this).attr('id'); //s03t04
      var tid = id.substr(id.indexOf("t")+1);
      if (old_tid != tid) {
        $("#t"+old_tid).removeClass("hover");
        $("#t"+tid).addClass("hover");
      }
      old_tid = tid;
    });

    //Seq Loop
    //jquery ui selectable
    /*
    $(".l").live('click', function(){
      var sid = $(this).parent().attr('id').substr(1);
      var url = "get-song-updates.lua";
      //renoise.song().transport.loop_sequence_range
      var data = {ajax:true, }
      var p = this;
      $.post(url, data, function(){
        $(".s").removeClass('scheduled');
        $(p).addClass('scheduled');
      });
      return false;
    });
    */

    //Set Schedule
    $(".s").live('click', function(){
      var sid = $(this).parent().attr('id').substr(1);
      var url = "/Seq. Triggering/Schedule/Sequence XX [Set]?i="+sid;
      var p = this;
      $.post(url, {ajax:true}, function(){
        $(".s").removeClass('scheduled');
        $(p).addClass('scheduled');
      });
      return false;
    });

    //Seq Trigger
    $(".pid").live('click', function(){
      var sid = $(this).parent().attr('id').substr(1);
      var url = "/Seq. Triggering/Trigger/Sequence XX [Set]?i="+sid;
      var p = this;
      $.post(url, {ajax:true});
      return false;
    });

    //Seq Mute
    $(".p").live('click', function(){
     var p = this

     var id = $(this).attr('id');
     var arr = id.match(/\d+/g);
     var seq = arr[0];
     var tid = arr[1];

     ~{do
       local url = Util:urlencode(
         "/Seq. Muting/Seq. XX [Toggle]/Seq. #seq/Mute Track #tid [Toggle]")
       url = url:gsub("%%23seq", "%%23'+seq+'")
       url = url:gsub("%%23tid", "%%23'+tid+'")
       OUT = ("var url = '%s';"):format(url)
     end }
     
     $.post(url, {ajax:true}, function(){
      $(p).toggleClass('seq_mute');
     });
     return false;
    });
  </script>
</body>
</html>
